package com.google.blockly.ohos.demo;

import com.google.blockly.ohos.demo.flyout.AlwaysOpenToolboxAbility;
import com.google.blockly.ohos.demo.flyout.NoCategoriesToolboxAbility;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.*;

/**
 * Entry ability for demos showing different flyout configurations.
 */

public class FlyoutDemos extends Ability {
    final static int[] DEMO_NAMES = {
            ResourceTable.String_no_categories_toolbox_ability_name,
            ResourceTable.String_always_open_toolbox_ability_name
    };

    final static Class[] DEMO_TARGETS = {
            NoCategoriesToolboxAbility.class,
            AlwaysOpenToolboxAbility.class
    };

    private LayoutScatter mHelium;
    private ListContainer mRecyclerView;

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_flyout_demo_list);
        mRecyclerView = (ListContainer) findComponentById(ResourceTable.Id_demo_list);
        mRecyclerView.setLayoutManager(new DirectionalLayoutManager());
        mRecyclerView.setItemProvider(new Adapter());
        mHelium = LayoutScatter.getInstance(this);
    }

    private class Adapter extends BaseItemProvider {

        @Override
        public int getCount() {
            return DEMO_NAMES.length;
        }

        @Override
        public Object getItem(int i) {
            return DEMO_NAMES[i];
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public Component getComponent(int i, Component component, ComponentContainer componentContainer) {
            ViewHolder viewHolder;
            if (component == null) {
                component = mHelium.parse(ResourceTable.Layout_list_text_item, null, false);
                viewHolder = new ViewHolder();
                viewHolder.itemView = (Text) component.findComponentById(ResourceTable.Id_text_item);
                component.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) component.getTag();
            }
            viewHolder.itemView.setText(getString(DEMO_NAMES[i]));
            viewHolder.itemView.setClickedListener(v -> {
                Intent intent = new Intent();
                Operation operation = new Intent.OperationBuilder()
                        .withBundleName(getBundleName())
                        .withAbilityName(DEMO_TARGETS[i])
                        .build();
                intent.setOperation(operation);
                startAbility(intent);
            });
            return component;
        }
    }

    private static class ViewHolder {
        public Text itemView;
    }
}
